#pragma once
#include <string>
#include <functional>

class TcpServer;
class Connection;
using func_t = std::function<void(Connection *)>;

class Connection
{
public:
    Connection(int sockfd, uint32_t events, TcpServer *R)
        : _sockfd(sockfd),
          _events(events),
          _R(R)
    {
    }
    ~Connection()
    {
    }

    void RegisterCallback(func_t recver, func_t sender, func_t excepter)
    {
        _recver = recver;
        _sender = sender;
        _excepter = excepter;
    }
    int Sockfd()
    {
        return _sockfd;
    }
    uint32_t Events()
    {
        return _events;
    }

    void SetEvents(uint32_t events)
    {
        _events = events;
    }

    void AddInBuffer(const std::string &buffer)
    {
        _inbuffer += buffer;
    }
    void AddOutBuffer(const std::string &buffer)
    {
        _outbuffer += buffer;
    }

    std::string &InBuffer()
    {
        return _inbuffer;
    }
    std::string &OutBuffer()
    {
        return _outbuffer;
    }

    bool OutBufferEmpty()
    {
        return _outbuffer.empty();
    }
    void Close()
    {
        ::close(_sockfd);
    }

private:
    int _sockfd;
    std::string _inbuffer;  // sockfd的接收缓冲区
    std::string _outbuffer; // sockfd的发送缓冲区

    // 关心的事件
    uint32_t _events;

public:
    // 读，写，异常的三个回调函数
    func_t _recver;
    func_t _sender;
    func_t _excepter;

    // 回调指针
    TcpServer *_R;
};

class ConnectionFactory
{
public:
    static Connection *BuildListenConnection(int sockfd, func_t recver, uint32_t events, TcpServer *R)
    {
        Connection *conn = new Connection(sockfd, events, R);
        conn->RegisterCallback(recver, nullptr, nullptr); // listen套接字只关心recver
        return conn;
    }

    static Connection *BuildNormalConnection(int sockfd, func_t recver,
                                             func_t sender,
                                             func_t excepter,
                                             uint32_t events, TcpServer *R)
    {
        Connection *conn = new Connection(sockfd, events, R);
        conn->RegisterCallback(recver, sender, excepter);
        return conn;
    }
};